

import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../http/api.dart';


class FaceCheck extends StatefulWidget {
  const FaceCheck({super.key, required this.dataList, required this.type});
  final List dataList;
  final int type;
  @override
  State<FaceCheck> createState() => _FaceCheckState();
}

class _FaceCheckState extends State<FaceCheck> {
  String isAgree ="0";

  String faceUrl="";
  String verufyToken="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUrlAction();
  }
  void getUrlAction()async{
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header+'api/system/dev/ocr/getFaceUrl',
      data: {
        "id_no":widget.dataList[1],
        "id_name":widget.dataList[0],
        "certificate_type":0,
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          setState(() {
            faceUrl=jsonMap['data']['url'];
            verufyToken=jsonMap['data']['verifyToken'];
          });


        }else{

        }
      });
    }).catchError((error) {
      print(error);
      ;
    });


  }
  Future<void> requestCameraPermission() async {
    var status = await Permission.camera.status;
    if (!status.isGranted) {
      await Permission.camera.request();

    }

  }
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("司机认证",style: TextStyle(fontWeight: FontWeight.w300),),
        centerTitle: true,
      ),
    body: Column(
      children: [
        Expanded(child: ListView(
          children: [
            SizedBox(height: 10.h,),
            Center(
              child: Text("为保障账户安全",style: TextStyle(color: Colors.black,fontSize: 24.sp,fontWeight: FontWeight.w600),),
            ),
            SizedBox(height: 10.h,),
            Center(
              child: Text("需采集您的人脸信息以核实身份",style: TextStyle(color: Colors.black,fontSize:16.sp,fontWeight: FontWeight.w300),),
            ),
            SizedBox(height: 40.h,),
            Center(

              child:
              Image.asset("lib/Images/Authentication/人脸识别.png",width: 170.w,height: 154.h,),
            ),

            SizedBox(height: 20.h,),

              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("·",style: TextStyle(color:Color.fromRGBO(242, 154, 44, 1),fontSize: 40.sp),),

                  Text("请正对屏幕并使脸位于取景框内          ",style: TextStyle(color:Color.fromRGBO(140, 139, 139, 1),fontSize: 15.sp),),
                ],
              ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("·",style: TextStyle(color:Color.fromRGBO(242, 154, 44, 1),fontSize: 40.sp),),

                Text("请保持光线充足，避免光照过强或过弱",style: TextStyle(color:Color.fromRGBO(140, 139, 139, 1),fontSize: 15.sp),),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("·",style: TextStyle(color:Color.fromRGBO(242, 154, 44, 1),fontSize: 40.sp),),

                Text("根据画面提示完成单个或多个动作检测",style: TextStyle(color:Color.fromRGBO(140, 139, 139, 1),fontSize: 15.sp),),
              ],
            ),


          ],


        ),
        ),
        Column(
          children: [
            Container(
              margin: EdgeInsets.only(left: 10, right: 10),
              padding: EdgeInsets.only(left: 10.w,right: 10.w),
              child: RichText(
                text: TextSpan(children: [
                  WidgetSpan(
                    alignment: PlaceholderAlignment.middle,
                    child: IconButton(
                      onPressed: () => {
                        setState(() {
                          if (isAgree == "1") {
                            isAgree = "0";
                          } else {
                            isAgree = "1";
                          }
                        })
                      },
                      icon:isAgree == "0" ? Icon(Icons.radio_button_unchecked): Icon(Icons.radio_button_checked),
                      color: isAgree == "1" ? Colors.orange : Colors.grey,
                    ),
                  ),
                  TextSpan(

                      text: '同意速配货处理人脸信息用于身份识别，人脸识别需要',
                      style: TextStyle(fontSize: 12, color: Colors.black54)),
                  TextSpan(
                      text: '使用相机权',
                      style: TextStyle(fontSize: 12, color: Colors.black54)),
                  TextSpan(
                      text: '限。查看',
                      style: TextStyle(fontSize: 12, color: Colors.black54)),
                  TextSpan(
                      text: '《人脸识别服务敏感个人信息处理规则》',
                      style: TextStyle(fontSize: 14, color: Colors.blue),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          // 查看 服务条款
                        }),

                ],),

              ),
            ),

            Container(
              height: 80.h,
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                      height: 40.h ,
                      margin: EdgeInsets.only(left: 15.w,right: 15.w),
                      decoration: BoxDecoration(
                          color:Color.fromRGBO(231, 112, 27, 0.85),
                          borderRadius: BorderRadius.all(Radius.circular(30))),

                      width: double.infinity,


                      child: TextButton(
                        child: Text("开始人脸识别",style: TextStyle(color: Colors.white,fontSize: 14.sp),),

                        onPressed: ()async{
                          if(faceUrl!="") {

                            // String? uid = await UserIdManager.getUserID();
                            // String successUrl = "http://192.168.3.9:8080/pages/success/success?token=$verufyToken&uid=$uid&type=1";
                            // String encodedSuccessUrl = Uri.encodeComponent(successUrl);
                            // String faildHeadUrl =  "http://192.168.3.9:8080/pages/failed/failed";
                            // String encodedFaildHeadUrl = Uri.encodeComponent(faildHeadUrl);
                            // Navigator.push(context,
                            //     MaterialPageRoute(builder: (context) {
                            //       return FaceCheckView(
                            //         url: faceUrl + "&successUrl=" + encodedSuccessUrl + "&failedUrl=" + encodedFaildHeadUrl, type: widget.type,);
                            //     }));
                            // Navigator.push(context,
                            //     MaterialPageRoute(builder: (context) {
                            //       return SMSView(
                            //         phoneNumber:  phoneNum, SMSCode: '', count:60,);
                            //     }));
                          }else{
                            BrnToast.show("人脸识别暂未初始化完成", context, duration: BrnDuration.short,);
                          }
                        },
                      )
                  ),
                ],
              ),
            ),

          ],
        )
      ],
    ),
    );
  }
}
